Gesture Recognizers
The UIGestureRecognizer
initializers and delegation wrappers
make it easy to add gesture recognizers to views. It also uses
closures instead of target-action and delegation.
Target-Action Initializers
The following is how you would add a double tap gesture recognizer to your view using one of the custom initializers. As always, we have a closure handler to respond to the gesture’s double tap action.
let doubleTapGesture = UITapGestureRecognizer(tapsRequired: 2) { _ in
log("double tapped")
}
view.addGestureRecognizer(doubleTapGesture)
These convenience initializers, delegate closures, and closure recognizers have been added to all of the existing concrete subclasses, including:
UITapGestureRecognizer
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UIPanGestureRecognizer
UIScreenEdgePanGestureRecognizer
UILongPressGestureRecognizer
There is also a method for you to configure a custom gesture recognizer to use closure handlers for recognition:
let myCustomGesture = MyCustomGestureRecognizer()
configure(gesture: myCustomGesture) { _ in
/// a closure that's called when the gesture has ended
}
Delegation
With convenient extension methods on UIGestureRecognizer
and UIView
,
we can daisy chain an entire gesture cycle, including responding
to UIGestureRecognizerDelegate
methods.
view
.addPanGesture() { pan in
guard pan.state == .ended else { return }
log("view panned")
}.shouldBegin() {
true
}.shouldRecognizeSimultaneouslyWith {
$0 === doubleTapGesture
}
-
Declaration
Swift
extension UIGestureRecognizer
-
Declaration
Swift
extension UITapGestureRecognizer
-
Declaration
Swift
extension UILongPressGestureRecognizer
-
Declaration
Swift
extension UIPinchGestureRecognizer
-
Declaration
Swift
extension UIPanGestureRecognizer
-
Declaration
Swift
extension UISwipeGestureRecognizer
-
Declaration
Swift
extension UIRotationGestureRecognizer
-
Declaration
Swift
extension UIScreenEdgePanGestureRecognizer
-
Declaration
Swift
extension UIView
-
This method is a convenience method to add a closure handler to a custom subclass of UIGestureRecognizer. If creating a custom gesture recognizer, you may want to also provide an initializer that takes a completion handler, just as the Closures framework provides for UIKit gesture recognizers.
An example of an initializer that adds closure support for recognition of custom gesture recognizer:
class MyCustomGestureRecognizer: UIGestureRecognizer { convenience init(handler: @escaping (_ gesture: MyCustomGestureRecognizer) -> Void) { self.init() configure(target: self, handler: handler) } }
Declaration
Swift
public func configure<T>(gesture: T, handler: @escaping (_ gesture: T) -> Void) where T: UIGestureRecognizer
Parameters
gesture
The UIGestureRecognizer that is being configured to use a closure in place of target-action.
handler
The closure that will be called when the gesture is recognized.